package cn.sccl.test;

import org.hibernate.Session;
import org.hibernate.Transaction;
import org.junit.Test;

import cn.sccl.domain.Customer;
import cn.sccl.utils.HibernateUtils;

/**
 * @author 饶爽
 * @time 2019年8月25日 下午9:43:34
 * @version 1.0.0
 * 测试hibernate一级缓存(session缓存)的类
*/
public class CacheDemo {
    @Test
    //证明一级缓存存在
    public void fun1() {
        //1.获得session
        Session session = HibernateUtils.openSession();
        //2.控制事务
        Transaction tx = session.beginTransaction();
        //3.执行操作
        Customer c1 = session.get(Customer.class, 1l);
        Customer c2 = session.get(Customer.class, 1l);
        Customer c3 = session.get(Customer.class, 2l);
        Customer c4 = session.get(Customer.class, 3l);
        
        System.out.println(c1==c2);//true
        System.out.println(c3==c4);//false
        //4.提交事务,关闭资源
        tx.commit();
        session.close();// 游离|托管 状态, 有id , 没有关联
    }
    
    @Test
    //同一个session缓存的数据以最后一个为准持久化到数据库
    public void fun2(){
        //1.获得session
        Session session = HibernateUtils.openSession();
        //2.控制事务
        Transaction tx = session.beginTransaction();
        //3.执行操作
        Customer c1 = session.get(Customer.class, 5l);
        
        c1.setCust_name("哈哈");
        c1.setCust_name("传智播客");
        
        //4.提交事务,关闭资源
        tx.commit();
        session.close();// 游离|托管 状态, 有id , 没有关联
    }
    @Test
    //持久化状态对象其实就是放入session缓存中的对象
    public void fun3(){
        //1.获得session
        Session session = HibernateUtils.openSession();
        //2.控制事务
        Transaction tx = session.beginTransaction();
        //3.执行操作
        Customer c1 = new Customer();
        c1.setCust_id(1l);//托管|游离
        
        session.update(c1);//c1被放入session缓存了
        
        @SuppressWarnings("unused")
        Customer c2 = session.get(Customer.class, 1l);
        
        //4.提交事务,关闭资源
        tx.commit();
        session.close();// 游离|托管 状态, 有id , 没有关联
    }
}
